package artid.com.arttogoa;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import artid.com.arttogoa.R;

import artid.com.arttogoa.adapter.GoodatAdapter;
import artid.com.arttogoa.adapter.StrericWheelAdapter;
import artid.com.arttogoa.barcode.Cache;
import artid.com.arttogoa.parser.NormalItem;
import artid.com.arttogoa.parser.PersonalMessageParse;
import artid.com.arttogoa.util.AlertUtils;
import artid.com.arttogoa.util.AppUtil;
import artid.com.arttogoa.util.BitmapUtil;
import artid.com.arttogoa.util.CameraUtils;
import artid.com.arttogoa.util.NetUtils;
import artid.com.arttogoa.util.VioceUtils;
import artid.com.arttogoa.view.WheelView;
import artid.com.arttogoa.volley.BitmapCache;
import artid.com.arttogoa.volley.VolleyBasic;
import artid.com.arttogoa.volley.VolleyCallback;
import artid.com.arttogoa.volley.VolleyData;
import artid.com.arttogoa.volley.VolleyMap;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.loopj.android.http.HttpGet;

import android.Manifest;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.view.animation.AnticipateOvershootInterpolator;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import artid.com.arttogoa.parser.OtherInformationParser;

/**
 * 
 *    
 * 项目名称：ArtworkArtA   
 * 类名称：EditMessageActivity   
 * 类描述：编辑信息   
 * 创建人：耿卫斌  
 * 创建时间：2016年5月16日 下午1:27:58      
 *
 */
public class EditMessageActivity extends BaseActivity implements
OnClickListener {
	private TextView mOk, edit_native_placetext, school_data_text;
	private RelativeLayout edit_native_place, school_data, autograph_layout;
	private ImageView autograph_image,iv_vioce;
	private String[] placeData = new String[34];
	private String[] schoolData = new String[10];
	private WheelView wheelView;
	private AlertDialog alertDialog;
	private GridView goodAtGrid;
	private String[] goodat = { "国画", "书法", "油画", "版画", "雕塑", "摄影", "当代艺术",
			"当代水墨", "水彩水粉", "其它" };
	private GoodatAdapter adapter;
	private Bitmap clipBitmap;//剪裁之后的图片
	private String Bitmap64;//剪裁之后的图片流
	Boolean isSetPic = false;
	private ImageLoader mImageLoader;
	private EditText info_memo;
	private EditText nameEd;
	private List<OtherInformationParser.OtherInformationParser_good> list_good;
	private List<OtherInformationParser.OtherInformationParser_university> list_university;
	private Handler mHandler=new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				try {
					Bitmap bm = (Bitmap)msg.obj;
					autograph_image.setImageBitmap(bm);
					Bitmap64= BitmapUtil.bitmaptoString(bm);
					conditionJudge();
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;

			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_edit_message);
		setContent(this, getIntent());
		setBack();
		//注册当前广播
		IntentFilter filter = new IntentFilter("com.EditMessageActivity.receiver");  
		registerReceiver(broadcastReceiver, filter);  
		mTittle = (TextView) findViewById(R.id.title_text);
		mContext = this;
		list_good=new ArrayList<OtherInformationParser.OtherInformationParser_good>();
		list_university=new ArrayList<OtherInformationParser.OtherInformationParser_university>();
		RequestQueue mQueue = Volley.newRequestQueue(mContext);
		mImageLoader = new ImageLoader(mQueue, new BitmapCache());
		mOk = (TextView) findViewById(R.id.edit_ok);
		edit_native_place = (RelativeLayout) findViewById(R.id.edit_native_place);
		edit_native_place.setOnClickListener(this);
		school_data = (RelativeLayout) findViewById(R.id.school_data);
		school_data.setOnClickListener(this);
		autograph_layout = (RelativeLayout) findViewById(R.id.autograph_layout);
		autograph_layout.setOnClickListener(this);
		edit_native_placetext = (TextView) findViewById(R.id.edit_native_placetext);
		school_data_text = (TextView) findViewById(R.id.school_data_text);
		autograph_image = (ImageView) findViewById(R.id.autograph_image);
		mTittle.setText("编辑信息");
		setBack();
		goodAtGrid = (GridView) findViewById(R.id.edit_gridview);
		info_memo = (EditText) findViewById(R.id.info_memo);
		nameEd = (EditText) findViewById(R.id.EditMessage_nameEd);
		nameEd.setText(AppUtil.getUser().getRealname());
		iv_vioce=(ImageView) findViewById(R.id.iv_vioce);
		nameEd.addTextChangedListener(mTextChangedListener);
		edit_native_placetext.addTextChangedListener(mTextChangedListener);
		school_data_text.addTextChangedListener(mTextChangedListener);
		info_memo.addTextChangedListener(mTextChangedListener);
		mBack.setOnClickListener(this);
		mOk.setOnClickListener(this);
		iv_vioce.setOnClickListener(this);
		if (AppUtil.getUser().getNative_place().equals("")) {
			edit_native_placetext.setText("籍贯");
		} else {
			edit_native_placetext.setText(AppUtil.getUser().getNative_place());
		}
		if (AppUtil.getUser().getUniversity().equals("")) {
			school_data_text.setText("毕业学院");
		} else {
			school_data_text.setText(AppUtil.getUser().getUniversity());
		}
		if (AppUtil.getUser().getMemo().equals("")) {
			info_memo.setText("");
		} else {
			info_memo.setText(AppUtil.getUser().getMemo());
		}

		ImageListener listener = ImageLoader
				.getImageListener(autograph_image,
						android.R.drawable.ic_menu_rotate,
						android.R.drawable.ic_delete);
		//		mImageLoader.get(AppUtil.getUser().getAutograph(), listener);
		initDate();
		initplaceData();
		initschoolData();
		if(AppUtil.getUser()!=null && !StringUtils.isEmpty(AppUtil.getUser().getAutograph())){
			getImage(AppUtil.getUser().getAutograph());
		}
		conditionJudge();
		if("1".equals(AppUtil.getUser().getIs_auth()) || "2".equals(AppUtil.getUser().getIs_auth())){
			//1已认证，2认证中姓名不可编辑
			nameEd.setFocusable(false);
			nameEd.setTextColor(Color.parseColor("#a5a5a5"));
		}
	}

	private void getImage(final String imgURL){
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				Bitmap bm = getBitmapFromUrl(imgURL);
				Message msg = mHandler.obtainMessage(1, bm);
				mHandler.sendMessage(msg);
			}
		}).start();
	}

	/**
	 * 获取擅长领域
	 */
	private void initDate() {
		ArrayList<HashMap<String, Object>> lstImageItem = new ArrayList<HashMap<String, Object>>();
		for (int i = 0; i < 10; i++) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("goodat", goodat[i]);
			map.put("bo", false);
			lstImageItem.add(map);
		}
		List<String> list=new ArrayList<String>();
		String goodat=AppUtil.getUser().getGood_at();
		if(!StringUtils.isEmpty(goodat)){
			String[] goodats = goodat.split(",");//他会把按.分开的部分存储到数组中
			for(int i=0; i<goodats.length; i++) { 
				list.add(goodats[i]);
			} 
		}
		adapter = new GoodatAdapter(list, mContext, lstImageItem);
		goodAtGrid.setAdapter(adapter);

	}

	/**
	 * 设置学院数据
	 */
	private void initschoolData() {
		schoolData[0] = "中央美院";
		schoolData[1] = "中国美院";
		schoolData[2] = "鲁迅美院";
		schoolData[3] = "四川美院";
		schoolData[4] = "西安美院";
		schoolData[5] = "清华美院";
		schoolData[6] = "广州美院";
		schoolData[7] = "天津美院";
		schoolData[8] = "湖北美院";
		schoolData[9] = "其他";
	}

	/**
	 * 设置城市数据
	 */
	private void initplaceData() {
		placeData[0] = "北京";
		placeData[1] = "天津";
		placeData[2] = "上海";
		placeData[3] = "重庆";
		placeData[4] = "河北";
		placeData[5] = "河南";
		placeData[6] = "云南";
		placeData[7] = "辽宁";
		placeData[8] = "黑龙江";
		placeData[9] = "湖南";
		placeData[10] = "安徽";
		placeData[11] = "山东";
		placeData[12] = "新疆维吾尔";
		placeData[13] = "江苏";
		placeData[14] = "浙江";
		placeData[15] = "江西";
		placeData[16] = "湖北";
		placeData[17] = "广西壮族";
		placeData[18] = "甘肃";
		placeData[19] = "山西";
		placeData[20] = "内蒙古";
		placeData[21] = "陕西";
		placeData[22] = "吉林";
		placeData[23] = "福建";
		placeData[24] = "贵州";
		placeData[25] = "广东";
		placeData[26] = "青海";
		placeData[27] = "西藏";
		placeData[28] = "四川";
		placeData[29] = "宁夏回族";
		placeData[30]="海南";
		placeData[31]="台湾";
		placeData[32]="香港";
		placeData[33]="澳门";
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.edit_ok:
			finishMessage();
			break;
		case R.id.edit_native_place:
			//籍贯选择
			initAlertDialog(1);
			break;
		case R.id.school_data:
			//学院选择
			initAlertDialog(2);
			break;
		case R.id.autograph_layout:
			//签名章图片选择
			showPopupWindow();
			break;
		case R.id.iv_vioce:
			//语音按钮
			VioceUtils vu = new VioceUtils(EditMessageActivity.this, iv_vioce, info_memo);
			vu.init();
			break;
		default:
			break;
		}
	}

	/**
	 * 条件判断
	 */
	private void conditionJudge(){
		if(!StringUtils.isEmpty(nameEd.getText().toString()) && !"籍贯".equals(edit_native_placetext.getText().toString()) && 
				!StringUtils.isEmpty(Bitmap64) && !"毕业学院".equals(school_data_text.getText().toString()) && 
				!StringUtils.isEmpty(info_memo.getText().toString())
//				 && !StringUtils.isEmpty(adapter.getCheckedVal())（根据需求暂时隐藏去掉擅长领域）
				){
			mOk.setEnabled(true);
			mOk.setBackgroundResource(R.drawable.red_frame);
		}else{
			mOk.setEnabled(false);
			mOk.setBackgroundResource(R.drawable.zjm_bg_dl);
		}
	}

	/**
	 * 对EditText监听
	 */
	TextWatcher mTextChangedListener = new TextWatcher() {  
		private CharSequence temp;  
		@Override  
		public void onTextChanged(CharSequence s, int start, int before, int count) {  
			// TODO Auto-generated method stub  
			temp = s;  
		}  

		@Override  
		public void beforeTextChanged(CharSequence s, int start, int count,  
				int after) {  
			// TODO Auto-generated method stub  
			//		          mTextView.setText(s);//将输入的内容实时显示  
		}  

		@Override  
		public void afterTextChanged(Editable s) {  
			// TODO Auto-generated method stub   
			//对按钮的判断是否可用
			conditionJudge();
		}  
	};  

	/**
	 * 编辑信息提交请求
	 */
	private void finishMessage() {
//		final String goodat = adapter.getCheckedVal();//获取到的擅长领域
		VolleyBasic.getInstance(EditMessageActivity.this).post(
				Cache.perfectinformation,
				VolleyMap.getInstance().perfectInformation(
						edit_native_placetext.getText().toString(), Bitmap64,
						"", school_data_text.getText().toString(),
						StringUtils.replace(info_memo.getText().toString(),"\"","”"),nameEd.getText().toString()), NormalItem.class,
						new VolleyCallback() {
					@Override
					public void onSuccess(VolleyData vd) {
						Log.d("log", vd.toString());
						PersonalMessage();

					}

					@Override
					public void onError(VolleyError volleyError) {

					}

				});
	}

	/**
	 * 获取更改后的艺术家信息并保存
	 */
	private void PersonalMessage(){
		VolleyBasic.getInstance(EditMessageActivity.this).post(
				Cache.editInformation,
				VolleyMap.getInstance().geteditInformation(), PersonalMessageParse.class,
				new VolleyCallback() {
					@Override
					public void onSuccess(VolleyData vd) {
						Log.d("log", vd.toString());
						PersonalMessageParse bean=(PersonalMessageParse) vd.getData();
						AppUtil.getUser().setAutograph(bean.getAutograph());
						AppUtil.getUser().setMemo(bean.getMemo());
						AppUtil.getUser().setUniversity(bean.getUniversity());
						AppUtil.getUser().setNative_place(bean.getNative_place());
						AppUtil.getUser().setGood_at(bean.getGood_at());
						AppUtil.getUser().setAutograph(bean.getAutograph());
						AppUtil.getUser().setRealname(nameEd.getText().toString());
						MainActivity.isRefreshPersonal=true;
						finish();
					}
					@Override
					public void onError(VolleyError volleyError) {

					}

				});
	}

	/**
	 * 滑动选择
	 * @param type
	 */
	private void initAlertDialog(final int type) {
		View view = LayoutInflater.from(EditMessageActivity.this).inflate(
				R.layout.pop_menu_type, null);
		wheelView = (WheelView) view.findViewById(R.id.timeWheel);
		if (type == 1) {
			wheelView.setAdapter(new StrericWheelAdapter(placeData));
		} else if (type == 2) {
			wheelView.setAdapter(new StrericWheelAdapter(schoolData));
		}
		wheelView.setCurrentItem(2);
		wheelView.setCyclic(true);
		wheelView.setInterpolator(new AnticipateOvershootInterpolator());

		view.findViewById(R.id.btnCancel).setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (alertDialog != null && alertDialog.isShowing()) {
							alertDialog.dismiss();
						}

					}
				});
		view.findViewById(R.id.btnConfirm).setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (alertDialog != null && alertDialog.isShowing()) {
							if (type == 1) {
								edit_native_placetext.setText(placeData[Integer
								                                        .valueOf(wheelView.getCurrentItem())]);
							} else if (type == 2) {
								school_data_text.setText(schoolData[Integer
								                                    .valueOf(wheelView.getCurrentItem())]);
							}
							alertDialog.dismiss();
						}

					}
				});

		alertDialog = new AlertDialog.Builder(EditMessageActivity.this)
		.create();
		alertDialog.show();

		WindowManager.LayoutParams params = alertDialog.getWindow()
				.getAttributes();
		params.width = EditMessageActivity.this.getWindowManager()
				.getDefaultDisplay().getWidth();
		int height = EditMessageActivity.this.getWindowManager()
				.getDefaultDisplay().getHeight();
		params.height = LayoutParams.WRAP_CONTENT;
		params.gravity = Gravity.BOTTOM;

		Window window = alertDialog.getWindow();
		window.setAttributes(params);
		window.setContentView(view);
		alertDialog.getWindow().setContentView(view);

	}

	/**
	 * 图片选择Dialog
	 */
	public void showPopupWindow() {
		AlertUtils.initPhotoAlertDialog(mContext,Integer.parseInt(NetUtils.getDisplayMetrics(EditMessageActivity.this).get(NetUtils.DM_WIDTH)), new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				switch (v.getId()) {
				case R.id.tv_phone:
					//检查权限
					if (ContextCompat.checkSelfPermission(EditMessageActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
						displayFrameworkBugMessageAndExit();
						return;
					}
					//照相机
					CameraUtils.openCameraImage(EditMessageActivity.this);
					AlertUtils.dismiss();
					break;
				case R.id.tv_choice:
					//从相册获取
					CameraUtils.openLocalImage(EditMessageActivity.this);
					AlertUtils.dismiss();
					break;
				default:
					break;
				}
			}
		});
	}

	/**
	 * 返回Activity参数处理
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
		// TODO Auto-generated method stub  
		super.onActivityResult(requestCode, resultCode, data);  
		if (requestCode == CameraUtils.GET_IMAGE_BY_CAMERA) {
			final Uri uri=CameraUtils.imageUriFromCamera;
			if(uri != null) {
				Intent i=new Intent(mContext,Clip_Activity.class);
				i.putExtra("ImagePath",  BitmapUtil.UriConversionAbsoluteURL(mContext, uri));
				startActivityForResult(i, 200);
			}else{
				//防止文件不会立马创建
				new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						if(uri != null) {
							Intent i=new Intent(mContext,Clip_Activity.class);
							i.putExtra("ImagePath", BitmapUtil.UriConversionAbsoluteURL(mContext, uri));
							startActivityForResult(i, 200);
						}
					}
				}, 1000);
			}
		} else if (requestCode == CameraUtils.GET_IMAGE_FROM_PHONE) {
			//判断是否从相册中获取图片
			if (data != null) {
				// 得到图片的全路径
				Uri uri = data.getData();
				Intent i=new Intent(mContext,Clip_Activity.class);
				i.putExtra("ImagePath", BitmapUtil.UriConversionAbsoluteURL(mContext, uri));
				startActivityForResult(i, 200);
			}
		} else if(requestCode==200){
			if(data!=null){
				//获取剪切后的图片路径
				String PhotoPath=data.getExtras().getString("PhotoPath");  
				if(!StringUtils.isEmpty(PhotoPath)){
					clipBitmap=BitmapUtil.getSmallBitmap(PhotoPath, 500, 500);
					//设置图片
					autograph_image.setImageBitmap(clipBitmap);
					Bitmap64= BitmapUtil.bitmaptoString(clipBitmap);
				}
			}
			conditionJudge();
		}
	}

	/**
	 * 使用HttpClient的get方式通过网络获取图片
	 * @param imageUrl
	 * @return
	 */
	public static Bitmap getBitmapFromUrl(String imageUrl){
		Bitmap result =null;
		try {
			HttpGet request =new HttpGet(imageUrl);
			HttpParams connParams =new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(connParams, 5*1000);
			HttpConnectionParams.setSoTimeout(connParams, 5*1000);
			HttpClient client =new DefaultHttpClient(connParams);
			try {
				HttpResponse resp =client.execute(request);
				if(resp.getStatusLine().getStatusCode() ==HttpStatus.SC_OK){
					HttpEntity entity = resp.getEntity();
					result =BitmapFactory.decodeStream(entity.getContent());
				}else{
					Log.d("TAG", "服务器响应异常");
				}
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				Log.d("TAG", e.getMessage()+"");
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				Log.d("TAG", e.getMessage()+"");
				e.printStackTrace();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return result;
	}


	//对开始接单的广播监听
	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {  

		@Override  
		public void onReceive(Context context, Intent intent) {  
			// TODO Auto-generated method stub  
			conditionJudge();
		}
	};

	/**
	 * 若摄像头被占用或者摄像头有问题则跳出提示对话框
	 */
	private void displayFrameworkBugMessageAndExit() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.app_name));
		builder.setMessage("请设置开启摄像头权限");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				NetUtils.getAppDetailSettingIntent(mContext);
			}
		});
		builder.show();
	}

	protected void onDestroy() {
		super.onDestroy();
		//关闭广播
		unregisterReceiver(broadcastReceiver);
	};
}
